{extend name="index/base" /}
{block name="style"}
<style type="text/css">
#treeview .jstree-container-ul .jstree-node {
  display: block;
  clear: both;
}
#treeview .jstree-leaf:not(:first-child) {
  float: left;
  background: none;
  margin-left: 0;
  width: 80px;
  clear: none;
}
#treeview .jstree-leaf {
  float: left;
  margin-left: 0;
  padding-left: 24px;
  width: 80px;
  clear: none;
  color: #777;
}
#treeview .jstree-leaf > .jstree-icon,
#treeview .jstree-leaf .jstree-themeicon {
  display: none;
}
#treeview .jstree-last {
  background-image: url("__IMG__/32px.png");
  background-position: -292px -4px;
  background-repeat: repeat-y;
}
#treeview .jstree-children:before,
#treeview .jstree-children:after {
  content: " ";
  display: table;
}
#treeview .jstree-children:after {
  clear: both;
}
#treeview .jstree-children:before,
#treeview .jstree-children:after {
  content: " ";
  display: table;
}
#treeview .jstree-children:after {
  clear: both;
}
#treeview .jstree-themeicon {
  display: none;
}
</style>
{/block}
{block name="body"}
<form class="layui-form"> 
  <div class="layui-form-item">
    <label class="layui-form-label">父级：</label>
    <div class="layui-input-block">
      <select name="row[pid]" lay-filter="parent" lay-verify="required" >
      <option value="">请选择他的爸爸，如果你不知道孩子父亲是谁，就选超级管理员...</option>
      {volist name="groupdata" id="vo"}
        <option value="{$key}">{$vo||html}</option>
      {/volist}
      
      </select>
    </div>
  </div>
  <div class="layui-form-item">
    <label class="layui-form-label">名称：</label>
    <div class="layui-input-inline">
      <input type="text" name="row[name]" value="{$row.name}" placeholder="取个名字，比如：财务" autocomplete="off" class="layui-input" lay-verify="required">
    </div>
  </div>
  <div class="layui-form-item">
    <label class="layui-form-label">权限：</label>
    <div class="layui-input-block">
      <input type="checkbox" lay-skin="primary" title="选中全部" lay-filter="checkall">
      <input type="checkbox" lay-skin="primary" title="展开全部" lay-filter="expandall">
      <br/>
      <div id="treeview"></div>
    </div>
  </div>
  <input type="hidden" name="row[rules]" value="" />
  <div class="layui-form-item layui-sumbtn">
	  <div class="layui-input-block">
	    <button class="layui-btn" lay-submit="" lay-filter="add">立即提交</button>
	    <button type="reset" class="layui-btn layui-btn-primary">重置</button>
	  </div>
  </div>
  
</form>
{/block}

{block name="script"}
<script type="text/javascript">
layui.use(['jstree','tool'],function(){
	var form=layui.form,
		$=layui.jquery,
		layer=layui.layer
    tool = layui.tool;
	form.on('select(parent)',function(data){
		var pid = '';
        var id = '';
        {notempty name="row"} 
        id={$row.id}; pid={$row.pid}; 
        {/notempty}
        if (data.value == id) {
            $("option[value='" + pid + "']", this).prop("selected", true).change();
            layer.msg('Can not change the parent to self',{icon:2});
            return false;
        }
        get_tree(id,data.value);
	});
  //读取选中的条目
    $.jstree.core.prototype.get_all_checked = function (full) {
        var obj = this.get_selected(), i, j;
        for (i = 0, j = obj.length; i < j; i++) {
            obj = obj.concat(this.get_node(obj[i]).parents);
        }
        obj = $.grep(obj, function (v, i, a) {
            return v != '#';
        });
        obj = obj.filter(function (itm, i, a) {
            return i == a.indexOf(itm);
        });
        return full ? $.map(obj, $.proxy(function (i) {
            return this.get_node(i);
        }, this)) : obj;
    };
	//get tree
  function get_tree(id,pid){
    $.ajax({
            url: "{:url('ajax/roletree')}",
            type: 'post',
            dataType: 'json',
            data: {id: id, pid: pid},
            success: function (ret) {
                if (ret.hasOwnProperty("code")) {
                    var data = ret.hasOwnProperty("data") && ret.data != "" ? ret.data : "";
                    if (ret.code === 1) {
                        //销毁已有的节点树
                        $("#treeview").jstree("destroy");
                        $("#treeview")
                        .on('redraw.jstree', function (e) {
                            $(".layer-footer").attr("domrefresh", Math.random());
                        })
                        .jstree({
                            "themes": {"stripes": true},
                            "checkbox": {
                                "keep_selected_style": false,
                            },
                            "types": {
                                "root": {
                                    "icon": "fa fa-folder-open",
                                },
                                "menu": {
                                    "icon": "fa fa-folder-open",
                                },
                                "file": {
                                    "icon": "fa fa-file-o",
                                }
                            },
                            "plugins": ["checkbox", "types"],
                            "core": {
                                'check_callback': true,
                                "data": data
                            }
                        });
                    } else {
                        layer.msg(ret.msg,{icon:2});
                    }
                }
            }, error: function (e) {
                layer.msg(e.message,{icon:2});
            }
        });
  }
	
	
	
	//全选和展开
	form.on('checkbox(checkall)', function(data){
		$("#treeview").jstree($(data.elem).prop("checked") ? "check_all" : "uncheck_all");
	});
	form.on('checkbox(expandall)', function(data){
		$("#treeview").jstree($(data.elem).prop("checked") ? "open_all" : "close_all");
	});

  var post_url = '{:url('add')}';
  {eq name='edit' value="1"}
      post_url = '{:url('edit',['ids'=>$row['id']])}';
      tool.setValue('row[pid]',{$row.pid});
      get_tree({$row.id},{$row.pid});
  {/eq}

	//提交
	form.on('submit(add)', function(data){
	  if ($("#treeview").size() > 0) {
	        var r = $("#treeview").jstree("get_all_checked");
	        data.field['row[rules]'] = r.join(',');
	        //$("input[name='row[rules]']").val(r.join(','));
	  }
    // console.log(data.field);return false;
	  $.post(post_url,data.field,function(ret){
	  	if (ret.code==1) {
	  		layer.msg(ret.msg,{icon:1,time:1000},function(){
          //关闭弹窗并刷新父窗口
          var frameid = $(window.parent.document).find('.layui-tab-item.layui-show iframe');
          frameid.attr('src',frameid.attr('src'));
          
          var index = parent.layer.getFrameIndex('group_add'); //先得到当前iframe层的索引
          parent.layer.close(index); //再执行关闭
        });
	  		
	  	}else{
	  		layer.msg(ret.msg,{icon:2});
	  	}
	  })
	  


	  
	  return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
	});

});
</script>

{/block}